package com.example.basics.examples;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class BlockingQueueExample {

    private static BlockingQueue<String> queue = new ArrayBlockingQueue<>(5);

    private static class Producer extends Thread {
        private int num;
        public Producer(int num){
            this.num = num;
        }

        @Override
        public void run() {
            try {
                queue.put("product" + num);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
//            System.out.print("produce..");
        }
    }

    private static class Consumer extends Thread {

        @Override
        public void run() {
            try {
                String product = queue.take();
                System.out.println(product);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
//            System.out.print("consume..");
        }
    }

    public static void main(String[] args) {
        //BlockingQueue 提供了阻塞的 take() 和 put() 方法：如果队列为空 take() 将阻塞，直到队列中有内容；如果队列为满 put() 将阻塞，直到队列有空闲位置。
        for (int i = 0; i < 2; i++) {
            Producer producer = new Producer(i);
            producer.start();
        }
        for (int i = 0; i < 5; i++) {
            Consumer consumer = new Consumer();
            consumer.start();
        }
        for (int i = 0; i < 3; i++) {
            Producer producer = new Producer(i);
            producer.start();
        }


    }
}
